package org.example.mynote.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.example.mynote.config.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {

    // 直接注入配置属性类
    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    public String uploadImage(MultipartFile file) throws IOException {
        // 从属性对象中获取配置信息
        String endpoint = aliyunOssProperties.getEndpoint();
        String accessKeyId = aliyunOssProperties.getAccessKeyId();
        String accessKeySecret = aliyunOssProperties.getAccessKeySecret();
        String bucketName = aliyunOssProperties.getBucketName();

        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // ... 后面的上传逻辑完全不变 ...
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String objectName = "images/" + datePath + "/" + UUID.randomUUID() + extension;

        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
